#include <iostream>
#include <fstream>
#include <google/protobuf/unknown_field_set.h>
#include "contacts.pb.h"

using namespace std;
using namespace c_contacts;
using namespace google::protobuf;

/**
 * 打印联系人列表
 */
void PrintContacts(const Contacts &contacts)
{
    for (int i = 0; i < contacts.contacts_size(); ++i)
    {
        const PeopleInfo &people = contacts.contacts(i);
        cout << "-------- 联系人 " << i + 1 << " --------" << endl;
        cout << "姓名：" << people.name() << endl;
        cout << "年龄：" << people.age() << endl;
        int j = 1;
        for (const PeopleInfo_Phone &phone : people.phone())
        {
            cout << "电话 " << j++ << "：" << phone.number() << endl;
        }
        cout << "--------------------------" << endl;

        // 打印未知字段
        const Reflection *reflection = PeopleInfo::GetReflection();
        const UnknownFieldSet &unknownSet = reflection->GetUnknownFields(people);
        for (int j = 0; j < unknownSet.field_count(); ++j)
        {
            const UnknownField& unknownField = unknownSet.field(j);
            cout << "未知字段" << j + 1 << "：" 
                 << "  字段编号：" << unknownField.number()
                 << "  类型：" << unknownField.type();
            switch(unknownField.type())
            {
                case UnknownField::Type::TYPE_VARINT:
                    cout << "  值：" << unknownField.varint() << endl;
                    break;
                case UnknownField::Type::TYPE_LENGTH_DELIMITED:
                    cout << "  值：" << unknownField.length_delimited() << endl;
                    break; 
            }
        }
    }
}

// demo8：测试 reserved
int main(int argc, char **argv)
{
    if (argc != 2)
    {
        cerr << "Usage: " << argv[0] << " CONTACTS_FILE" << endl;
        return -1;
    }

    // 以二进制的方式读取 contacts
    Contacts contacts;
    fstream input(argv[1], ios::in | ios::binary);
    if (!contacts.ParseFromIstream(&input))
    {
        cerr << "Failed to parse contacts." << endl;
        input.close();
        return -1;
    }

    // 打印 contacts
    PrintContacts(contacts);

    input.close();
    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}